package com.bawei.library_net.interceptor

import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.library_common.utils.DataStoreUtils
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @Author : 
 * @Time : On 2023/6/26 11:01
 * @Description : TokenInterceptor
 */
class TokenInterceptor:Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()//原始的request请求
        val builder = request.newBuilder()
        //token从DataStore中读取数据：
        val token = DataStoreUtils.getData("token", "")
        if(!token.isBlank()){//不为空
            val newRequest =builder .header("token", token).build()//token请求头添加的新的request
            val response = chain.proceed(newRequest)//执行结果response
            if(response.code() == 401){//身份验证失败，token过期，跳转到登陆页面
               ARouter.getInstance().build("").navigation()
            }else{//身份验证成功
                return response //添加请求头
            }
        }
        return chain.proceed(request)

    }
}